package com.sunday.android.fangdaifu.bukong.fragment.index;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.sunday.android.fangdaifu.bukong.R;
import com.sunday.android.fangdaifu.bukong.activity.index.DoOptionActivity;
import com.sunday.android.fangdaifu.bukong.adapter.EquipOptionAdapter;
import com.sunday.android.fangdaifu.bukong.adapter.EquipmentWithHeadersAdapter;
import com.sunday.android.fangdaifu.bukong.entity.BindBack;
import com.sunday.android.fangdaifu.bukong.entity.Option;
import com.sunday.android.fangdaifu.bukong.entity.event.DoSearch;
import com.sunday.android.fangdaifu.bukong.http.ApiClient;
import com.sunday.android.fangdaifu.bukong.utils.LazyFragment;
import com.sunday.android.fangdaifu.bukong.utils.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.NoScrollListview;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 * 设备匹配
 */
public class OptinFragment extends LazyFragment {

    @Bind(R.id.tvSelect)
    TextView tvSelect;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.emptylayout)
    EmptyLayout emptylayout;
    @Bind(R.id.tvBtn)
    TextView tvBtn;
    @Bind(R.id.tv1)
    TextView tv1;
    @Bind(R.id.lSelect)
    View lSelect;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    private EquipOptionAdapter adapter;
    List<Option> options = new ArrayList<>();
    private Option selectOption;

    private boolean isPrepared;
    private boolean mHasLoadedOnce;
    private LinearLayoutManager layoutManager;

    private String plantNo;
    private int type;
    private long id;//point id

    public OptinFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_option, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle bundle = getArguments();
        type = bundle.getInt("type");
        id = bundle.getLong("id");//point id
        initView();
        isPrepared = true;
        lazyLoad();
        handleRecycle();
    }

    // 初始化布局
    private void initView() {
        tvBtn.setClickable(false);
        tvBtn.setSelected(false);
        refreshLayout.setColorSchemeResources(R.color.material_red, R.color.material_green,
                R.color.material_blue, R.color.material_yellow);
        layoutManager = new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new EquipOptionAdapter(mContext,options);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).color(Color.parseColor("#999999")).build());
        adapter.setSelect(new EquipOptionAdapter.OnOpenListener() {
            @Override
            public void toggle(int key, boolean select,Option option) {
                tv1.setVisibility(View.VISIBLE);
                lSelect.setVisibility(View.VISIBLE);
                selectOption = option;
                tvSelect.setText(selectOption.getPlantNo());
                tvBtn.setClickable(true);
                tvBtn.setSelected(true);
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNo = 1;
                getData();
            }
        });
    }

    private void getData(){
        loading();
        Call<ResultDO<List<Option>>> call = ApiClient.getApiAdapter().AfChoosePlant(plantNo,type,pageNo,pageSize);
        call.enqueue(new Callback<ResultDO<List<Option>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Option>>> call, Response<ResultDO<List<Option>>> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    if (pageNo==1){
                        options.clear();
                    }
                    options.addAll(response.body().getResult());
                    if (response.body().getResult().size()==pageSize){
                        pageNo++;
                        isCanloadMore=true;
                    }else {
                        isCanloadMore=false;
                    }
                    if (options.isEmpty()){
                        emptylayout.setErrorType(EmptyLayout.NODATA);
                        emptylayout.setErrorMessage("暂无数据");
                    }else {
                        emptylayout.setVisibility(View.GONE);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Option>>> call, Throwable t) {
                if (isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
            }
        });
    }

    private int pageNo = 1, pageSize = 10;
    private boolean isCanloadMore = false;
    private int lastVisibleItem;
    private void handleRecycle() {
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNo = 1;
                getData();
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE &&
                        lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    pageNo++;
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                isCanloadMore = dy > 0;
            }
        });
    }

    @OnClick(R.id.tvBtn)
    public void onViewClicked() {
        if (selectOption==null){return;}
        bind();
    }

    //可见后加载数据
    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
        mHasLoadedOnce = true;
        getData();
    }

    private void bind(){
        showLoadingDialog(0);
        Call<ResultDO<BindBack>> call
                = ApiClient.getApiAdapter().AgBindPlant(selectOption.getId(),id);
        call.enqueue(new Callback<ResultDO<BindBack>>() {
            @Override
            public void onResponse(Call<ResultDO<BindBack>> call, Response<ResultDO<BindBack>> response) {
                dissMissDialog();
                if (response.body() == null || isFinish) {
                    return;
                }
                if (response.body() != null && response.body().getCode() == 0) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("bind",response.body().getResult());
                    intent = new Intent(mContext, DoOptionActivity.class);
                    intent.putExtra("id",id);
                    intent.putExtra("plantId",selectOption.getId());
                    intent.putExtra("bind",bundle);
                    startActivity(intent);
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<BindBack>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, "网络错误");
            }
        });
    }

    private void loading(){
        if (!refreshLayout.isRefreshing()){
            refreshLayout.setRefreshing(true);
        }
    }

    public void doSearch(DoSearch doSearch){
        plantNo = doSearch.content;
        getData();
    }

    public static OptinFragment instance(int type,long id) {
        OptinFragment fragment = new OptinFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        bundle.putLong("id", id);//point id
        fragment.setArguments(bundle);
        return fragment;
    }

}
